package simorg.actions;

import simorg.controller.UserController;
import simorg.domain.Course;
import simorg.domain.User;
import simorg.domain.persistence.CourseTable;
import simorg.domain.persistence.StudentCourseJoinTable;
import simorg.domain.persistence.UserTable;
import simorg.view.Flash;
import simorg.view.ModelView;
import simorg.view.WebSessionContext;

public class UserUnenroll extends Action {

	public static String actionName = "unenroll";
	public UserUnenroll() {
		super(actionName);
		this.controllerName = UserController.controllerName;
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		Course courseToEnroll = CourseTable.findById(wc.getDbConnection(), Integer.parseInt(wc.getRequestParameter("courseId")));
		int studentid = Integer.parseInt(this.getRequestArgs().get(0));
		User student = UserTable.findById(wc.getDbConnection(), studentid);
		Flash flash = new Flash("unenrollment_result");
		flash.getValues().put("message", student.getUsername() + " unenrolled.");
		wc.addFlash(flash);
		StudentCourseJoinTable.remove(wc.getDbConnection(), studentid, courseToEnroll.getId());
		Action redirect = new CourseView(String.valueOf(courseToEnroll.getId()));
		wc.redirectAdmin(redirect);
		return null;
	}

}
